//
//  AllKindsOfTableViewController.m
//  Travelmemory
//
//  Created by lanou3g on 16/3/31.
//  Copyright © 2016年 ABCD. All rights reserved.
//

#import "AllKindsOfTableViewController.h"
#import "AllKindsOfTableViewCell.h"
#import "NearModel.h"
#import "SingleHelper.h"
#import <MapKit/MapKit.h>
#import "TravelHelper.h"
#import "UIImageView+WebCache.h"
#import "SceneryViewController.h"
#import "MJRefresh.h"
@interface AllKindsOfTableViewController ()

@property (nonatomic, strong) NSMutableArray *allArray;
@end

static int page = 0;
@implementation AllKindsOfTableViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    // navigation背景
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBar"] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.title = @"我的附近";
    
    self.allArray = [NSMutableArray array];
    
    //    网络请求
    if ([self.title isEqualToString:@"全部"]) {
        [self category:0 start:page];
    } else if([self.title isEqualToString:@"景点"]){
        [self category:11 start:page];
    }else if([self.title isEqualToString:@"住宿"]){
        [self category:10 start:page];
    }else if([self.title isEqualToString:@"餐厅"]){
        [self category:5 start:page];
    }else if ([self.title isEqualToString:@"休闲娱乐"]){
        [self category:21 start:page];
    }else if ([self.title isEqualToString:@"购物"]){
        [self category:6 start:page];
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:@"AllKindsOfTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerAction)];
    [self.tableView addFooterWithTarget:self action:@selector(footerAction)];
    
}


-(void)headerAction{

    //NSLog(@"------%d %d" ,count, sender);
    NSString *lat = [NSString stringWithFormat:@"%f", [[SingleHelper defaultHunterCityHelper].userLocation coordinate].latitude];
    NSString *lng = [NSString stringWithFormat:@"%f", [[SingleHelper defaultHunterCityHelper].userLocation coordinate].longitude];
    int count = 0;
    int sender = 0;
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/place/pois/nearby/?keyword=&category=%d&start=%d&count=20&latitude=%@&longitude=%@&sign=c5eda95c3e8eeb231801c7f70637b724",count,sender,lat,lng];
    //    NSLog(@"%@",str);
    [[TravelHelper defaultTravelHelper] get:str params:nil success:^(id responseObj) {
        //NSLog(@"%@", responseObj);
        for (NSDictionary *dic in responseObj[@"items"]) {
            NearModel *model = [NearModel new];
            
            [model setValuesForKeysWithDictionary:dic];
            [model setValue:dic[@"id"] forKey:@"ID"];
            [self.allArray addObject:model];
            
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
        
        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络链接失败,请查看网络连接" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        
        [view show];
        
    }];

    [self.tableView headerEndRefreshing];

}
#pragma mark ---------------下拉有问题-----------
-(void)footerAction{

    //NSLog(@"------%d %d" ,count, sender);
    NSString *lat = [NSString stringWithFormat:@"%f", [[SingleHelper defaultHunterCityHelper].userLocation coordinate].latitude];
    NSString *lng = [NSString stringWithFormat:@"%f", [[SingleHelper defaultHunterCityHelper].userLocation coordinate].longitude];
    int count = 0;
    int sender = 0;
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/place/pois/nearby/?keyword=&category=%d&start=%d&count=20&latitude=%@&longitude=%@&sign=c5eda95c3e8eeb231801c7f70637b724",count,sender,lat,lng];
    //    NSLog(@"%@",str);
    [[TravelHelper defaultTravelHelper] get:str params:nil success:^(id responseObj) {
        //NSLog(@"%@", responseObj);
        for (NSDictionary *dic in responseObj[@"items"]) {
            NearModel *model = [NearModel new];
            
            [model setValuesForKeysWithDictionary:dic];
            [model setValue:dic[@"id"] forKey:@"ID"];
            [self.allArray addObject:model];
            
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
        
        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络链接失败,请查看网络连接" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        
        [view show];
        
    }];
    
    [self.tableView headerEndRefreshing];

}

#pragma mark --- 网络请求
- (void)category:(int)count start:(int)sender{
    
    //NSLog(@"------%d %d" ,count, sender);
    NSString *lat = [NSString stringWithFormat:@"%f", [[SingleHelper defaultHunterCityHelper].userLocation coordinate].latitude];
    NSString *lng = [NSString stringWithFormat:@"%f", [[SingleHelper defaultHunterCityHelper].userLocation coordinate].longitude];
    
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/place/pois/nearby/?keyword=&category=%d&start=%d&count=20&latitude=%@&longitude=%@&sign=c5eda95c3e8eeb231801c7f70637b724",count,sender,lat,lng];
//    NSLog(@"%@",str);
    [[TravelHelper defaultTravelHelper] get:str params:nil success:^(id responseObj) {
        //NSLog(@"%@", responseObj);
        for (NSDictionary *dic in responseObj[@"items"]) {
            NearModel *model = [NearModel new];
            
            [model setValuesForKeysWithDictionary:dic];
            [model setValue:dic[@"id"] forKey:@"ID"];
            [self.allArray addObject:model];
            
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {

       
       UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络链接失败,请查看网络连接" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
       
       [view show];
        
    }];
    
    [self.tableView footerEndRefreshing];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//
//    return 1;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.allArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AllKindsOfTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NearModel *model = self.allArray[indexPath.row];
    
    [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_s] placeholderImage:[UIImage imageNamed:@"cat"]];
    
    cell.UpLabel.text = model.name;
    
    cell.MiddleLabel.numberOfLines = 2;
    
    cell.MiddleLabel.text = model.Description;
    
    if (model.distance < 1) {
        cell.DistanceLabel.text = [NSString stringWithFormat:@"%.0fM",model.distance*1000];
    } else{
        cell.DistanceLabel.text = [NSString stringWithFormat:@"%.0fKM",model.distance];
    }
    
    cell.HowMany.text = [NSString stringWithFormat:@"%@人",model.visited_count];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 118;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SceneryViewController *scenery = [SceneryViewController new];
    NearModel *model = self.allArray[indexPath.row];
    scenery.ID = model.ID;
    scenery.name = model.name;
    scenery.cover_s = model.cover_s;
    
    [self.navigationController pushViewController:scenery animated:YES];
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
